package Day12;

class ListNode{
    ListNode next;
    int val;

    public ListNode(int val) {
        this.val = val;
    }
}
public class Test2 {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        ListNode f = pHead1;
        ListNode s = pHead2;
        while(!(f == null || s == null)){
            f = f.next;
            s = s.next;
        }
        int count = 0;
        if(s == null){
            while(f != null){
                f = f.next;
                count++;
            }
            f = pHead1;
            s = pHead2;
            while(count != 0){
                f = f.next;
                count--;
            }
        }else{
            while(s != null){
                s = s.next;
                count++;
            }
            f = pHead1;
            s = pHead2;
            while(count != 0){
                s = s.next;
                count--;
            }
        }
        while(f != s){
            f = f.next;
            s = s.next;
            if(f == null || s == null){
                return null;
            }
        }
        return s;
    }
}
